package com.letoken.platform.pub.annotation.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.letoken.platform.pub.constant.RedisKeyConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Map;

import static com.letoken.platform.pub.enums.LetokenApiResponseEnum.ERROR_MALL_SMS_005;

@Slf4j
@Component
public class VerityCodeValidator implements ConstraintValidator< VerityCodeCheck, Object> {



    private String accountKey;
    private String typeKey;
    private Integer errorCount;
    private Integer sendCount;

    @Autowired
    StringRedisTemplate stringRedisTemplate;




    @Override
    public void initialize(VerityCodeCheck constraintAnnotation) {
        accountKey = constraintAnnotation.accountKey();
        typeKey = constraintAnnotation.typeKey();
        errorCount = constraintAnnotation.errorCount();
        sendCount = constraintAnnotation.sendCount();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context ) {
        if (StringUtils.isEmpty(accountKey)  || StringUtils.isEmpty(typeKey)){
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("Parameter error").addConstraintViolation();
            return false;
        }
        /* 从请求对象中获取手机号和验证码的字段名 */
        Map<String,Object> map = JSONObject.parseObject(JSON.toJSONString(value));
        String account = (String) map.get(accountKey);
        Integer type = (Integer) map.get(typeKey);



        VerifyCodeType verifyCodeType = VerifyCodeType.getInstance(type);

        /* 验证码获取频繁  */
        String countKey = String.format(RedisKeyConstant.APP_SMS_CODE_SEND_COUNT,verifyCodeType.getType(),account);
        String vk = stringRedisTemplate.opsForValue().get(countKey);
        if (StringUtils.isNotBlank(vk)){
            Integer v = Integer.valueOf(vk);
            v = v == null ? 0 : v;
            if (v > sendCount){
                context.disableDefaultConstraintViolation();
//                context.buildConstraintViolationWithTemplate(String.format("验证码获取频繁，请%s分钟后再试",verifyCodeType.getLimitTime()/60)).addConstraintViolation();
                context.buildConstraintViolationWithTemplate(ERROR_MALL_SMS_005.getDesc()).addConstraintViolation();
                return false;
            }
        }

        return true;

    }








}
